from PySide6.QtCore import QThread, Signal

class BaseThread(QThread):
    received = Signal(str)
    error = Signal(str)
    connected = Signal(bool)
    
    def __init__(self):
        QThread.__init__(self)
        self._is_running = False
    
    def _connect(self):
        """建立连接的抽象方法，子类必须实现"""
        raise NotImplementedError("子类必须实现_connect方法")
    
    def _disconnect(self):
        """断开连接的抽象方法，子类必须实现"""
        raise NotImplementedError("子类必须实现disconnect方法")
    
    def write(self, data):
        """发送数据的抽象方法，子类必须实现"""
        raise NotImplementedError("子类必须实现write方法")
    
    def is_connected(self):
        """检查连接状态的抽象方法，子类必须实现"""
        raise NotImplementedError("子类必须实现is_connected方法")
    
    def get_connection_info(self):
        """获取连接信息的抽象方法，子类必须实现"""
        raise NotImplementedError("子类必须实现get_connection_info方法")
    
    def run(self):
        """线程运行的基本流程"""
        if not self._connect():
            return
            
        while self._is_running:
            try:
                self._read_data()
            except Exception as e:
                if self._is_running:
                    self.error.emit(str(e))
                break
        
        self.disconnect()
    
    def _read_data(self):
        """读取数据的抽象方法，子类必须实现"""
        raise NotImplementedError("子类必须实现_read_data方法")